<template>
  <div class="calendar">
    <div class="calendar-header">
      <h2 class="calendar-title">智慧农事日历</h2>
      <div class="navigation">
        <button class="nav-button" @click="previousMonth">
          <i class="el-icon-arrow-left"></i>
        </button>
        <span class="back-to-today" @click="goToToday">返回今日</span>
        <div class="month-display">
          <span class="current-month">{{ currentYear }}年{{ currentMonth }}月</span>
          <div class="month-controls">
            <button class="month-control-btn up" @click="nextMonth">
              ▲
            </button>
            <button class="month-control-btn down" @click="previousMonth">
              ▼
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <div class="calendar-subheader">
      <div class="legend">
        <div class="legend-item">
          <span class="legend-color prevention"></span>
          <span>预防期</span>
        </div>
        <div class="legend-item">
          <span class="legend-color outbreak"></span>
          <span>高发期</span>
        </div>
        <div class="legend-item">
          <span class="legend-color critical"></span>
          <span>关键期</span>
        </div>
      </div>
      <div class="week-indicator">第{{ currentWeek }}周</div>
    </div>
    
    <div class="weekdays">
      <div v-for="(day, index) in weekdays" :key="index" class="weekday">{{ day }}</div>
    </div>
    
    <div class="days">
      <div
        v-for="(day, index) in calendarDays"
        :key="index"
        class="day"
        :class="{
          'outside-month': !day.currentMonth,
          'today': day.isToday,
          'selected': selectedDay && selectedDay.day === day.day && selectedDay.currentMonth === day.currentMonth
        }"
        @click="selectDay(day)"
      >
        <span class="day-number">{{ day.day }}</span>
        <span class="lunar-date">{{ day.lunarDate }}</span>
        <div v-if="day.events.length" class="event-indicators">
          <span
            v-for="(type, typeIndex) in getEventTypes(day.events)"
            :key="typeIndex"
            class="event-indicator"
            :class="type"
          ></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';

// 当前日期
const currentDate = ref(new Date());
// 选中的日期
const selectedDay = ref(null);
// 星期天到星期六的中文表示
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

// 计算当前年份
const currentYear = computed(() => {
  return currentDate.value.getFullYear();
});

// 计算当前月份（1-12）
const currentMonth = computed(() => {
  return currentDate.value.getMonth() + 1;
});

// 计算当前周数（以年初为第1周）
const currentWeek = computed(() => {
  const firstDayOfYear = new Date(currentDate.value.getFullYear(), 0, 1);
  const pastDaysOfYear = (currentDate.value - firstDayOfYear) / 86400000;
  return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
});

// 计算日历天数
const calendarDays = computed(() => {
  const year = currentDate.value.getFullYear();
  const month = currentDate.value.getMonth();
  const firstDayOfMonth = new Date(year, month, 1);
  const lastDayOfMonth = new Date(year, month + 1, 0);
  const daysInMonth = lastDayOfMonth.getDate();
  
  const firstWeekday = firstDayOfMonth.getDay();
  let prevMonthDays = firstWeekday;
  
  const days = [];
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 上个月的日期
  if (prevMonthDays > 0) {
    const prevMonth = new Date(year, month, 0);
    const daysInPrevMonth = prevMonth.getDate();
    
    for (let i = prevMonthDays - 1; i >= 0; i--) {
      const day = daysInPrevMonth - i;
      const date = new Date(year, month - 1, day);
      days.push({
        day,
        date,
        currentMonth: false,
        isToday: date.getTime() === today.getTime(),
        lunarDate: getLunarDate(date),
        events: getEvents(date)
      });
    }
  }
  
  // 本月的日期
  for (let day = 1; day <= daysInMonth; day++) {
    const date = new Date(year, month, day);
    days.push({
      day,
      date,
      currentMonth: true,
      isToday: date.getTime() === today.getTime(),
      lunarDate: getLunarDate(date),
      events: getEvents(date)
    });
  }
  
  // 下个月的日期
  const remainingDays = 42 - days.length; // 6行7列共42个日期
  for (let day = 1; day <= remainingDays; day++) {
    const date = new Date(year, month + 1, day);
    days.push({
      day,
      date,
      currentMonth: false,
      isToday: date.getTime() === today.getTime(),
      lunarDate: getLunarDate(date),
      events: getEvents(date)
    });
  }
  
  return days;
});

// 上一个月
function previousMonth() {
  const date = new Date(currentDate.value);
  date.setMonth(date.getMonth() - 1);
  currentDate.value = date;
  selectedDay.value = null;
  updateCalendar();
}

// 下一个月
function nextMonth() {
  const date = new Date(currentDate.value);
  date.setMonth(date.getMonth() + 1);
  currentDate.value = date;
  selectedDay.value = null;
  updateCalendar();
}

// 返回今日功能
function goToToday() {
  const today = new Date();
  currentDate.value = today;
  
  // 查找今天对应的日历数据
  const todayData = calendarDays.value.find(day => day.isToday);
  selectedDay.value = todayData;
  
  // 通知父组件日期已重置
  emit('daySelected', todayData);
  updateCalendar();
}

// 选择日期
function selectDay(day) {
  selectedDay.value = day;
  
  // 发射事件，通知父组件天数被选中
  emit('daySelected', day);
}

// 初始化日历状态变量
const daysInMonth = ref(0);
const firstDayOfMonth = ref(0);
const days = ref([]);

// 更新日历
function updateCalendar() {
  // 重新计算日历数据
  daysInMonth.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth() + 1,
    0
  ).getDate();
  
  firstDayOfMonth.value = new Date(
    currentDate.value.getFullYear(),
    currentDate.value.getMonth(),
    1
  ).getDay();
  
  // 强制刷新日历视图
  days.value = [];  // 清空数组，强制calendarDays重新计算
}

// 获取农历日期（简化版）
function getLunarDate(date) {
  // 这里简化处理，实际应该使用专门的农历计算库
  const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
    '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
    '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
  
  // 这里用一个简单的映射代替真实的农历计算
  const day = (date.getDate() + date.getMonth() * 2) % 30;
  return lunarDays[day];
}

// 获取某天的事件（示例数据）
function getEvents(date) {
  const events = [];
  
  // 获取日期组件
  const year = date.getFullYear();
  const month = date.getMonth();
  const day = date.getDate();
  
  // 2025年全年的事件
  if (year === 2025) {
    // 每个月按规律生成特定日期的事件
    // 每月的1日、3日、5日为固定事件（除了4月份只有1日和5日）
    const fixedDays = month === 3 ? [1, 5] : [1, 3, 5]; 
    
    // 基本事件类型
    if (fixedDays.includes(day)) {
      let eventType = 'prevention';
      let eventTitle = '月初茶园普查';
      
      if (day === 3) {
        eventType = 'outbreak';
        eventTitle = '茶小绿叶蝉监测';
      } else if (day === 5) {
        eventType = 'prevention';
        eventTitle = '茶小绿叶蝉预防';
      }
      
      events.push({
        date: new Date(year, month, day),
        type: eventType,
        title: eventTitle
      });
      return events;
    }
    
    // 其他日期的事件：按月份分布，确保每个月有15-20天有防治措施
    const monthlyDays = {
      0: [7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31], // 1月
      1: [2, 4, 8, 10, 12, 14, 18, 20, 22, 24, 26, 28], // 2月
      2: [7, 8, 10, 11, 13, 14, 16, 18, 19, 21, 22, 24, 25, 27, 28, 30, 31], // 3月
      3: [2, 4, 6, 9, 12, 15, 16, 18, 20, 22, 24, 26, 28, 30], // 4月
      4: [1, 3, 5, 8, 10, 12, 14, 17, 20, 22, 23, 25, 27, 29, 31], // 5月
      5: [2, 4, 7, 9, 11, 13, 16, 18, 20, 22, 25, 27, 29], // 6月
      6: [1, 3, 5, 7, 10, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31], // 7月
      7: [2, 4, 6, 8, 11, 14, 16, 18, 20, 22, 24, 26, 28, 30], // 8月
      8: [2, 4, 6, 8, 10, 12, 14, 17, 19, 21, 23, 25, 27, 29], // 9月
      9: [1, 3, 5, 7, 9, 11, 13, 15, 18, 21, 23, 25, 27, 29, 31], // 10月
      10: [2, 4, 6, 8, 10, 12, 15, 18, 20, 22, 24, 26, 28, 30], // 11月
      11: [2, 4, 6, 9, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] // 12月
    };
    
    // 检查当前日期是否在本月的事件日期列表中
    if (monthlyDays[month] && monthlyDays[month].includes(day)) {
      // 基于日期确定类型
      let type;
      // 设置特殊日期
      if (day === 19) {
        type = 'outbreak'; // 确保19日为高发期
      } else {
        // 按照一定规律分配类型
        const types = ['prevention', 'outbreak', 'critical'];
        const index = Math.floor((month * 31 + day) % 3);
        type = types[index];
      }
      
      events.push({
        date: new Date(year, month, day),
        type: type,
        title: '茶园病虫害防治'
      });
    }
  } else {
    // 为当前月份（非2025年）提供默认示例事件
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 为最近一周的日期添加示例事件
    if (Math.abs(date - today) < 7 * 24 * 60 * 60 * 1000) {
      const dayOfWeek = date.getDay();
      
      if (dayOfWeek % 3 === 0) {
        events.push({
          date: new Date(date),
          type: 'prevention',
          title: '茶小绿叶蝉预防'
        });
      } else if (dayOfWeek % 3 === 1) {
        events.push({
          date: new Date(date),
          type: 'outbreak',
          title: '红蜘蛛监测'
        });
      } else {
        events.push({
          date: new Date(date),
          type: 'critical',
          title: '茶毛虫防治'
        });
      }
    }
  }
  
  return events;
}

// 格式化选中日期
function formatSelectedDate() {
  if (!selectedDay.value) return '';
  return `${selectedDay.value.date.getFullYear()}年${selectedDay.value.date.getMonth() + 1}月${selectedDay.value.date.getDate()}日 ${selectedDay.value.lunarDate}`;
}

// 获取事件类型
function getEventTypes(events) {
  return [...new Set(events.map(event => event.type))];
}

// 定义输出事件
const emit = defineEmits(['daySelected']);
</script>

<style scoped>
.calendar {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  padding: 6px 8px 10px 8px;
  font-family: Arial, sans-serif;
  height: 100%;
  width: 50%;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3px;
}

.calendar-title {
  font-size: 14px;
  font-weight: 600;
}

.navigation {
  display: flex;
}

.nav-button {
  background: none;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
}

.nav-button:hover {
  background-color: #f5f5f5;
}

.back-to-today {
  margin: 0 10px;
  font-size: 12px;
  color: #1989fa;
  cursor: pointer;
  font-weight: normal;
  padding: 2px 8px;
  border-radius: 4px;
  background-color: #ecf5ff;
}

.back-to-today:hover {
  background-color: #dbedff;
}

.month-display {
  display: flex;
  align-items: center;
  margin: 0 10px;
}

.current-month {
  font-size: 14px;
  font-weight: 500;
  margin-right: 8px;
}

.month-controls {
  display: flex;
  flex-direction: column;
  gap: 0; /* 移除按钮间隙 */
}

.month-control-btn {
  background: none;
  border: none;
  padding: 0;
  cursor: pointer;
  border-radius: 2px;
  width: 16px;
  height: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 8px;
  line-height: 1;
  margin: 0;
}

.month-control-btn.up {
  margin-bottom: -1px; /* 使按钮稍微重叠 */
  border-bottom: 1px solid #f0f0f0; /* 添加微妙的分隔线 */
}

.month-control-btn:hover {
  background-color: #f0f0f0;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  margin-bottom: 2px;
}

.weekday {
  padding: 3px 0;
  font-size: 12px;
  color: #666;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 6px;
  margin-bottom: 0;
}

.day {
  position: relative;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  font-size: 13px;
}

.day:hover {
  background-color: #f0f2f5;
}

.day.outside-month {
  opacity: 0.5;
}

.day.today {
  font-weight: bold;
  border: 1px solid #e6f7ff;
  background-color: #e6f7ff;
}

.day.selected {
  background-color: #e6f7ff;
  border: 1px solid #1890ff;
}

.lunar-date {
  font-size: 10px;
  color: #999;
  margin-top: 2px;
}

.event-indicators {
  position: absolute;
  bottom: 1px;
  display: flex;
  gap: 1px;
}

.event-indicator {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin: 0 1px;
}

.event-indicator.prevention {
  background-color: #4CAF50; /* 绿色 - 预防期 */
}

.event-indicator.outbreak {
  background-color: #2196F3; /* 蓝色 - 高发期 */
}

.event-indicator.critical {
  background-color: #FF9800; /* 橙色 - 关键期 */
}

.legend {
  display: flex;
  justify-content: center;
  margin-top: 5px;
  gap: 10px;
}

.legend-item {
  display: flex;
  align-items: center;
  font-size: 10px;
  color: #666;
}

.legend-color {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
}

.legend-color.prevention {
  background-color: #4CAF50; /* 绿色 - 预防期 */
}

.legend-color.outbreak {
  background-color: #2196F3; /* 蓝色 - 高发期 */
}

.legend-color.critical {
  background-color: #FF9800; /* 橙色 - 关键期 */
}

.calendar-subheader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3px;
}

.week-indicator {
  font-size: 12px;
  color: #666;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
}
</style> 